// pages/tweets.js
// 云开发里记得设置权限    
const db = wx.cloud.database()
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: false,
    collectionProjectsInfo: [],
    collectionRecord: [],
  },

  // -----------------------------------



  // 页面跳转
  getBackMine() {
    wx.navigateBack({
      delta: 1
    });
  },


  // 递归查项目信息
  findProjectInfo(arr, i, collectionProjectsInfo) {
    if (arr.length === 0) {
      return
    }
    wx.showLoading({
      title: '请稍后',
    })
    let that = this;
    db.collection('projects').where({
      _id: arr[i].uuid
    }).get({
      success: res => {
        if (res.data.length != 0) {
          collectionProjectsInfo.push(res.data[0])
        }
        if (arr.length != i + 1) {
          return that.findProjectInfo(arr, i + 1, collectionProjectsInfo);
        } else {
          that.setData({
            collectionProjectsInfo,
            isShow: true,
          });
          console.log(that.data.collectionProjectsInfo);
        };
        wx.hideLoading();
      }
    })
  },
  cancelCollect(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let arr = this.data.collectionProjectsInfo;
    arr.splice(index, 1)
    this.setData({
      collectionProjectsInfo: arr
    });
    console.log(that.data.collectionRecord[index]);
    db.collection('userCollect').doc(that.data.collectionRecord[index]._id).remove({
      success: res => {
        let arr2 = that.data.collectionRecord;
        arr2.splice(index, 1);
        that.setData({
          collectionRecord: arr2
        })
      },
      fail: res => {
        console.log(res);
      }
    });
  },

  navToProjectDetail(e) {
    console.log(e.currentTarget.dataset.item);
    let project_detail = e.currentTarget.dataset.item;
    app.navTmpInfo = project_detail;
    wx.navigateTo({
      url: '/pages/project_detail/project_detail',
    })
  },

  refreshData() {
    let that = this;
    db.collection('userCollect').where({
      _openid: app.personInfo._openid,
      type: '项目'
    }).get({
      success: function (res) {
        if (res.data.length === 0) {
          that.setData({
            isShow: false,
          })
        } else {
          that.setData({
            collectionRecord: res.data

          })
          let collectionProjectsInfo = [];
          that.findProjectInfo(res.data, 0, collectionProjectsInfo);
        }
      }
    })

  },
  // -----------------------------------
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.refreshData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})